import EventEmitter from 'node:events'
import { WebSocket, WebSocketServer } from 'ws'
import { ApiMsgEnum, IModel } from '../Common'
import { Connection } from './Connection'

export class MyServer extends EventEmitter {
  port: number
  wss: WebSocketServer
  connections: Set<Connection> = new Set()
  apiMap: Map<ApiMsgEnum, Function> = new Map()

  constructor({ port }: { port: number }) {
    super()
    this.port = port
  }

  // 启动服务
  start() {
    return new Promise((resolve, reject) => {
      this.wss = new WebSocketServer({ port: this.port })

      this.wss.on('listening', () => {
        resolve(true)
      })
      this.wss.on('close', () => {
        reject(false)
      })
      this.wss.on('error', error => {
        reject(error)
      })
      this.wss.on('connection', (ws: WebSocket) => {
        const connection = new Connection(this, ws)
        this.connections.add(connection)
        this.emit('connection', connection)

        connection.on('close', () => {
          this.connections.delete(connection)
          this.emit('disconnection', connection)
        })
      })
    })
  }

  // 设置api
  setApi<T extends keyof IModel['api']>(name: T, cb: (connection: Connection, args: IModel['api'][T]['req']) => void) {
    this.apiMap.set(name, cb)
  }
}
